import re
import cgi

# URL expression lifted from url_to_hyperlink of PloneBoard.
urlmatcher = re.compile(
    r"\b(?P<url>(?P<scheme>http|https|mailto):(?P<interfix>//)"
    r"(?:(?P<login>(?P<username>[a-zA-Z0-9]+)(?::(?P<password>[A-Za-z0-9]+))?)@)?"
    r"(?P<hostname>[A-Za-z0-9.-]+(?::(?P<port>[0-9]+))?)"
    r"(?P<path>[A-Za-z0-9@~_=?/.&;%#+-]*))",
    re.I)

def render_raw_message(message):
    """Return a basic rendering of the given message suitable for viewing in a
    browser.

    >>> render_raw_message('http://message/with/a/url')
    '<a href="http://message/with/a/url">http://message/with/a/url</a>'

    >>> render_raw_message('<example>')
    '&lt;example&gt;'
    """
    message = cgi.escape(message)
    message = urlmatcher.sub(r'<a href="\1">\1</a>', message)
    return message
